﻿using System.Reflection;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class MonsterDrop : MonoBehaviour, IDropHandler, IPointerEnterHandler, IPointerExitHandler
{
    public Image containerImage;
    private Color normalColor;
    public Color highlightColor = Color.yellow;
    private bool isHaveChild = false;

    //public void OnEnable()
    //{
    //    if (containerImage != null)
    //        normalColor = containerImage.color;

    //}

    public void OnDrop(PointerEventData data)
    {
        if (data.pointerDrag.tag == "EnemyFood")
            return;

        if (data.pointerDrag.name != TeamManager._instance.PlayerFoods[PlayerAttack._instance.MainAttack].foodGo.name)
            return;

        if (isHaveChild == true)
        {
            isHaveChild = false;
            return;
        }

        Sprite dropSprite = GetDropSprite(data);
        if (dropSprite != null)
        {
            FoodInfo foodInfo = ReadXml._instance.GetFoodBySpriteName(dropSprite.name);

            Food food = TeamManager._instance.GetPlayerFoodById(foodInfo.ID);

            MapGridView mapgridview = this.transform.GetComponent<MapGridView>();

            TeamManager._instance.PlayerFoods[PlayerAttack._instance.MainAttack].SetGoPos(mapgridview.MapGridPosX, mapgridview.MapGridPoxY);
            MapManager._instance.ClearMapGridState();
            MapManager._instance.ShowRange(TeamManager._instance.PlayerFoods[PlayerAttack._instance.MainAttack]);

            //MapManager._instance.ClearMapGridState();
            //MapManager._instance.SetMapGridRed(TeamManager._instance.PlayerFoods[PlayerAttack._instance.MainAttack]);
        }

    }

    public void OnPointerEnter(PointerEventData data)
    {
        if (containerImage == null)
            return;

        if (containerImage != null)
            normalColor = containerImage.color;

        Sprite dropSprite = GetDropSprite(data);
        if (dropSprite != null && data.pointerDrag.tag != "EnemyFood" && data.pointerDrag.name == TeamManager._instance.PlayerFoods[PlayerAttack._instance.MainAttack].foodGo.name)
            containerImage.color = highlightColor;

        if (containerImage.transform.childCount > 0)
            isHaveChild = true;
    }



    public void OnPointerExit(PointerEventData data)
    {
        if (containerImage == null)
            return;

        containerImage.color = normalColor;
    }

    private Sprite GetDropSprite(PointerEventData data)
    {
        var originalObj = data.pointerDrag;
        if (originalObj == null)
            return null;

        var srcImage = originalObj.GetComponent<Image>();
        if (srcImage == null)
            return null;

        return srcImage.sprite;
    }
}